package com.clusterswisdom.horn.api.tmall.formate;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.ioc.struct.StructConfig;
import com.clusterswisdom.horn.api.ioc.struct.StructFormatter;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.taobao.api.domain.Refund;
import com.taobao.api.domain.Trade;
import com.taobao.api.response.TradeGetResponse;

public class RefundFormatter implements StructFormatter {
	
	public static final String TYPE_ALL = "M540";

	public static final String TYPE_DEPART = "M541";
	
	@Override
	public JSONObject format(Object object, StructConfig config) {
		Refund refund = (Refund)object;
		
		JSONObject returnRefund = new JSONObject();
		returnRefund.put("ttradeId", refund.getTid() == null ? "" : refund.getTid().toString());
		returnRefund.put("torderId", refund.getOid() == null ? "" : refund.getOid().toString());
		returnRefund.put("trefundType", refund.getTotalFee().equals(refund.getRefundFee()) ? TYPE_ALL : TYPE_DEPART);
		returnRefund.put("trefundId", refund.getRefundId().toString());
		returnRefund.put("torderStatus", refund.getOrderStatus());
		returnRefund.put("refundTotal", refund.getTotalFee());
		returnRefund.put("refundReason", refund.getReason());
		returnRefund.put("refundDesc", refund.getDesc());
		returnRefund.put("refundStatus", refund.getStatus());
		returnRefund.put("refundNum", refund.getNum().toString());
		returnRefund.put("alipayNo", refund.getAlipayNo());
		try {
			returnRefund.put("alipayTime", getTrade(refund.getTid()).getCreated());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return returnRefund;
	}

	private Trade getTrade(Long tid) throws Exception {
		JSONObject param = new JSONObject();
		param.put("tid", tid);
		
		TradeGetResponse response = (TradeGetResponse)TmallInstance.getInstance().executeRequest(param, "trade", "tradeGet");
		return response.getTrade();
	}
}
